from PepsDownloader import PepsSentinelDownloader

import datetime
import os
import inspect
import sqlalchemy
import urllib.parse


class Postgreslq(object):
    
    def __init__(self,host,port,database,username,password):
        self.host = host
        self.port = port
        self.database = database
        self.username = username
        self.password = password
    
    def __enter__(self):
        self.url = sqlalchemy.engine.URL.create(
            drivername='postgresql',  #  postgresql+psycopg2/postgresql/postgresql+pg8000
            username=self.username,
            password=urllib.parse.quote_plus(self.password),  
            host=self.host,
            port=self.port,
            database=self.database) 
        self.engine = sqlalchemy.create_engine(
            self.url,
            encoding='utf8',
            echo=False,
            # pool_reset_on_return=None,
            pool_recycle=3600,
            pool_size=10, 
            pool_pre_ping=True,
            max_overflow=0)
        self.conn = self.engine.connect()
        return self
    
    def getresult(self,sql,result):
        strings = sql.split(" ")
        string_1 = strings[0]
        words = string_1.split('\n')
        maxword = words[0]
        word = maxword.lower()
        data = result.fetchall() if word == "select" else None
        return data
    
    def sqlString(self,sql):
        result = self.conn.execute(sql)
        result = self.getresult(sql,result)
        return result

    def __exit__(self, exceptionType, exceptionVal, trace):
        self.conn.close()
        self.engine.dispose()

def process_info(func):
    def warpper(*args,**kwargs):
        print(f"进程ID：{os.getpid()}")
        print(f"文件路径：{inspect.getfile(func)}")
        print(f"函数名称：{func.__name__}")
        print(f"传入参数({func.__code__.co_argcount})：{args}  {kwargs}")
        print(f"起始时间：{datetime.datetime.now()}  {'**'*20}")
        
        start_date = datetime.datetime.now()
        result = func(*args,**kwargs)
        end_date = datetime.datetime.now()
        
        print(f"结束时间：{datetime.datetime.now()}  {'=='*20}")
        print(f'耗时：{end_date - start_date}s')
        return result
    return warpper   

def func(args): return args[0](*args[1])

def getXmonthafter(months,date_=None):
    if date_ is None:
        date_=datetime.date.today()
    yeardelta=(date_.month+months-1)//12
    newmonth=(date_.month+months-1)%12+1
    return datetime.date(date_.year+yeardelta,newmonth,1)

def date_split_by_month(days=30):
    # start_date = start_date.strftime('%Y-%m-%d')
    # end_date = end_date.strftime('%Y-%m-%d')
    # start_date = datetime.datetime.strptime(start_date,"%Y-%m-%d")
    # end_date = datetime.datetime.strptime(end_date,"%Y-%m-%d")
    start_date = datetime.datetime.now() - datetime.timedelta(days=days)
    end_date =  datetime.datetime.now()
    
    month_s=(end_date.year-start_date.year)*12+(end_date.month-start_date.month)+1
    
    dates = []
    for i in range(month_s):
        if i == 0:
            month_endday=getXmonthafter(1,start_date)
            dates.append([start_date.strftime("%Y-%m-%d"),month_endday.strftime("%Y-%m-%d")])
        elif i==month_s-1:
            month_startday=getXmonthafter(i,start_date)
            # end_date = end_date+datetime.timedelta(days=1)-datetime.timedelta(seconds=1)
            dates.append([month_startday.strftime("%Y-%m-%d"),end_date.strftime("%Y-%m-%d")])
        else:
            month_startday=getXmonthafter(i,start_date)
            month_endday=getXmonthafter(i+1,start_date)+datetime.timedelta(seconds=1)
            dates.append([month_startday.strftime("%Y-%m-%d"),month_endday.strftime("%Y-%m-%d")])
    return dates


@process_info
def main(qhdms,days,folder,pgargs):
    cloud = 100
    dates = date_split_by_month(days)
    
    with Postgreslq(*pgargs) as PG:
        sql = f"""select distinct tile
                from china_gygrid
                where qhdm in {str(tuple(qhdms))};
                """
        data = PG.sqlString(sql)
        tiles = [i for i, in data]
        
    with PepsSentinelDownloader() as PSD:
        for sdate,edate in dates:
            yearmonth =  datetime.datetime.strptime(sdate,"%Y-%m-%d").strftime("%Y%m")
            save_dir = os.path.join(folder,yearmonth)
            if not os.path.exists(save_dir):os.makedirs(save_dir)
            for tile in tiles: 
                PSD.tileDownloader(tile,sdate,edate,save_dir,cloud)
                
    return

if __name__ == "__main__":
    username='postgres'
    password='postgres'
    host="192.168.2.172"
    port='5432'
    database='sentinel2'
    pgargs = host,port,database,username,password

    qhdms = ['13','37','41']
    cloud = 100
    days = 10
    folder = r'/home/homes/Sentinel2Zip'
    
    main(qhdms,days,folder,pgargs)